package com.oneday.ashop.console.base.shiro.filter;

import com.oneday.ashop.console.authority.AuthService;
import com.oneday.ashop.console.base.shiro.spring.SpringCacheManagerWrapper;
import com.oneday.ashop.console.base.web.MyContextLoaderListener;
import com.oneday.ashop.core.base.util.CollectionUtil;
import com.oneday.ashop.core.entity.Admin;
import com.oneday.ashop.core.entity.Resource;
import com.oneday.ashop.core.entity.Role;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.PostConstruct;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 资源过滤器
 * Created by admin on 2016/7/4.
 */
@Slf4j
@Component
@Lazy(value = false)
//@Data
public class BaseResourceFilter  extends AuthorizationFilter {

    /**
     * 请求路径的父级的路径
     */
    public static final String REQ_URI_PARENT_KEY = "req_uri_parent";
    /**
     * 请求路径的名字
     */
    public static final String REQ_URI_KEY = "req_uri";
    /**
     * 请求登陆页面
     */
    public static final String LOGIN_PAGE_REQ = "/auth/get_login_page.htm";
    /**
     * 主页面请求
     */
    public static final String HOME_PAGE_REQ = "/auth/home_page.htm";
    /**
     * 主页面菜单
     */
    public static final String HOME_PAGE_MENU = "home_page_menu";



    //路径和资源的映射
    public static Map<String, Resource> resourceMap = new HashMap<>();

    //资源和角色的映射
    public static Map<Integer, List<String>> resourceAndRolesMap = new HashMap<>();


    @Autowired(required = false)
    private AuthService authService;

    /**
     * 初始化资源和角色
     */
    public synchronized  void init() {
        log.info("初始化资源过滤器...");
        List<Resource> resources = authService.getALlResources();
        Map<Integer, Resource> idAndResourceMap = CollectionUtil.buildMap(resources, Integer.class, Resource.class, "id");
        for(Resource resource : resources) {
            if(idAndResourceMap.containsKey(resource.getParentId())) {
                resource.setParentName(idAndResourceMap.get(resource.getParentId()).getName());
            }
            resourceMap.put(resource.getUrl(), resource);
        }
        //初始化资源和角色的映射
        List<Role> roles = authService.getAllRoles();
        for(Role role : roles) {
            List<Integer> resourceIds = role.getResources();
            if(resourceIds == null) {
                break;
            }
            for(Integer resourceId : resourceIds) {
                if(resourceAndRolesMap.containsKey(resourceId) &&  !resourceAndRolesMap.get(resourceId).contains(role.getName())) {
                    resourceAndRolesMap.get(resourceId).add(role.getName());
                }else {
                    List<String> roleNames = new ArrayList<>();
                    roleNames.add(role.getName());
                    resourceAndRolesMap.put(resourceId, roleNames);
                }
            }
        }
        log.info("初始化资源过滤器完成！");
    }


    /**
     * 判断该请求是否有权限（能进入到这里除了登陆的请求，其他的请求都是在登陆的情况下进来的，且不对json请求进行拦截）
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        //判断是否有此路径
        String uri = ((HttpServletRequest)servletRequest).getRequestURI();
        String extendName = uri.substring(uri.indexOf(".") + 1);

        //登陆请求和json请求不做拦截
        if(uri.equals(BaseResourceFilter.LOGIN_PAGE_REQ) || uri.equals("/") || "json".equals(extendName)) {
            return true;
        }

        //除了登陆页面之后，统一设置菜单和用户名
        servletRequest.setAttribute(HOME_PAGE_MENU, getMenu());
        servletRequest.setAttribute(BaseUserLoginFilter.REQ_USER_NAME, ((Admin)subject.getPrincipal()).getName());

        //主页面不做拦截
        if(uri.equals(HOME_PAGE_REQ)) {
            return true;
        }

        //判断是否包含请求资源
        if(!HOME_PAGE_REQ.equals(uri) && !resourceMap.containsKey(uri)) {
            return false;
        }

        //设置页面请求信息
        servletRequest.setAttribute(REQ_URI_KEY, uri); //设置请求路径
        if(HOME_PAGE_REQ.equals(uri)) { //如果请求的是主页面，直接通过
         return true;
        }

        servletRequest.setAttribute(REQ_URI_PARENT_KEY, resourceMap.get(uri).getParentName()); //设置父级路径

        //设置超级管理权限
        if(((Admin)subject.getPrincipal()).getName().equals("admin")) {
            return true;
        }

        //查找该资源被拥有的角色
        List<String> roleNames = resourceAndRolesMap.get(resourceMap.get(uri).getId());
        if(roleNames == null || roleNames.size() == 0) {
            return false;
        }
        boolean[] checkResult = subject.hasRoles(roleNames);
        for(boolean flag : checkResult) {
            if(flag) {
                return true;
            }
        }
        return false;
    }


    //获得菜单
    public  List<Resource> getMenu() {
        List<Resource> resources = new ArrayList<>();
        for(String key : resourceMap.keySet()) {
            resources.add(resourceMap.get(key));
        }
        //一级资源的集合
        Map<Integer, Resource> resourceMap = new HashMap<>();
        //二级资源的集合
        Map<Integer, List<Resource>> secondResourceMap = new HashMap<>();
        for(Resource resource : resources) {
            //判断该用户是否拥有该资源
            List<String> roleNames = resourceAndRolesMap.get(resource.getId());
            if(roleNames == null) {
                continue;
            }
            boolean roleFlag = false; //判断该用户是否拥有该资源的角色中的一个角色，只要有一个该flag就是true
            //遍历该资源拥有的角色
            for(boolean flag : SecurityUtils.getSubject().hasRoles(roleNames)) {
                if(flag) {
                    roleFlag = flag;
                    continue;
                }
            }
            //是否应该跳过该资源，只要没有拥有拥有该资源的角色中的一个，就跳过该资源，认为该用户没有访问该资源的权限
            if(!roleFlag) {
                continue;
            }
            if(resource.getLevel() == 1) {
                resourceMap.put(resource.getId(), resource);
            }else {
                if(secondResourceMap.containsKey(resource.getParentId())) {
                    secondResourceMap.get(resource.getParentId()).add(resource);
                }else {
                    List<Resource> tempResource = new ArrayList<>();
                    tempResource.add(resource);
                    secondResourceMap.put(resource.getParentId(), tempResource);
                }
            }
        }
        //遍历一级资源
        List<Resource> result = new ArrayList<>();
        for(Integer key : resourceMap.keySet()) {
            resourceMap.get(key).setChildRes(secondResourceMap.get(key));
            result.add(resourceMap.get(key));
        }
        return result;
    }
}
